package org.study.redis.search.boot.document;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年04月27日
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/student")
public class StudentController {
    private final StudentRepository studentRepository;

    @PostMapping
    public Student saveStudent(@RequestBody Student student) {
        return studentRepository.save(student);
    }

    @GetMapping
    public Student getStudent(@RequestParam(value = "name", required = false) String name,
                              @RequestParam(value = "searchLastName", required = false) String searchLastName) {
        if (StringUtils.isNotBlank(name)) {
            return this.studentRepository.findByName(name)
                    .orElseThrow(() -> new RuntimeException("Student not found"));
        }
        if (StringUtils.isNotBlank(searchLastName)) {
            return this.studentRepository.searchByLastName(searchLastName)
                    .orElseThrow(() -> new RuntimeException("Student not found"));
        }
        return null;
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity handleError(RuntimeException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
    }
}
